package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	name string
	age  int8
}

func NewPerson(name string, age int8) *Person {
	return &Person{
		name: name,
		age:  age,
	}
}

// Person的Dream方法
func (p Person) Dream() {
	fmt.Printf("%s的梦想是学好Go语言\n", p.name)
}

// 指针类型
func (p *Person) SetAge(newage int8) {
	p.age = newage
}

// 使用值接收者
func (p Person) SetAge2(newage int8) {
	p.age = newage
}

func JsonDemo() {
	type Student struct {
		ID     int
		Gender string
		Name   string
	}
	type Class struct {
		Title    string
		Students []*Student
	}
	c := &Class{
		Title:    "101",
		Students: make([]*Student, 0, 200),
	}
	for i := 0; i < 10; i++ {
		stu := &Student{
			ID:     i,
			Gender: "男",
			Name:   fmt.Sprintf("stu%02d", i),
		}
		c.Students = append(c.Students, stu)
	}
	// JSON 序列化 ： 结构体 -> JSON格式的字符串
	data, err := json.Marshal(c)
	if err != nil {
		fmt.Println("json marshal failed")
		return
	}
	fmt.Printf("json:%s\n", data) // json:{"Title":"101","Students":[{"ID":0,"Gender":"男","Name":"stu00"},{"ID":1,"Gender":"男","Name":"stu01"},{"ID":2,"Gender":"男","Name":"stu02"},{"ID":3,"Gender":"男","Name":"stu03"},{"ID":4,"Gender":"男","Name":"stu04"},{"ID":5,"Gender":"男","Name":"stu05"},{"ID":6,"Gender":"男","Name":"stu06"},{"ID":7,"Gender":"男","Name":"stu07"},{"ID":8,"Gender":"男","Name":"stu08"},{"ID":9,"Gender":"男","Name":"stu09"}]}

	// JSON 反序列化
	str := `{"Title":"101","Students":[{"ID":0,"Gender":"男","Name":"stu00"},{"ID":1,"Gender":"男","Name":"stu01"},{"ID":2,"Gender":"男","Name":"stu02"},{"ID":3,"Gender":"男","Name":"stu03"},{"ID":4,"Gender":"男","Name":"stu04"},{"ID":5,"Gender":"男","Name":"stu05"},{"ID":6,"Gender":"男","Name":"stu06"},{"ID":7,"Gender":"男","Name":"stu07"},{"ID":8,"Gender":"男","Name":"stu08"},{"ID":9,"Gender":"男","Name":"stu09"}]}`
	c1 := &Class{}
	err = json.Unmarshal([]byte(str), c1)
	if err != nil {
		fmt.Println("json unmarshal failed!")
		return
	}
	fmt.Printf("%#v\n", c1)
}

func TagDemo() {
	type Student struct {
		ID     int `json:"id"` // 通过指定tag实现json序列化该字段时的key
		Gender string
		name   string // 私有不能被json包访问
	}
	s1 := Student{
		ID:     1,
		Gender: "男",
		name:   "老六",
	}
	data, err := json.Marshal(s1)
	if err != nil {
		fmt.Println("json marshal failed!")
		return
	}
	fmt.Printf("json str:%s\n", data)
}

func main() {
	p1 := NewPerson("老六", 23)
	p1.Dream()          // 老六的梦想是学好Go语言
	fmt.Println(p1.age) // 23
	p1.SetAge(30)
	fmt.Println(p1.age) // 30

	p2 := NewPerson("老王", 56)
	fmt.Println(p2.age) // 56
	p2.SetAge2(30)      // (*p2).SetAge2(30)
	fmt.Println(p2.age) // 56

	JsonDemo()
	TagDemo()

}
